<?php

// 积分商城

namespace app\shop\controller;

use think\Db;
use think\Session;
use think\Request;
use think\Controller;
use app\shop\model\Member as MemberModel;
use app\shop\model\GoodsType as GoodsTypeModel;
use app\shop\model\IntegralGoods as IntegralGoodsModel;
use app\shop\model\IntegralRecord as IntegralRecordModel;
use app\shop\model\MemberAddress as MemberAddressModel;

class Integral extends Controller
{
    /**
     * 积分商城
     * @param Request $request
     * @param MemberModel $member
     * @param IntegralRecordModel $integralRecord
     * @return mixed
     */
    public function index(Request $request, MemberModel $member, IntegralRecordModel $integralRecord)
    {
        // 获取会员ID
        $userId = Session::get('member_id');
        $inquire = $request->param();

        // 筛选
        $condition['member_id'] = $userId;
        if (!empty($inquire['type'])) $condition['type_id'] = $inquire['type'];

        // 积分记录
        $records = $integralRecord->where($condition)->order(['create_time' => 'desc'])->paginate(20, false)->toArray();

        // 会员积分
        $integral = $member->where(['id' => $userId])->value('integral');


        return $this->fetch('', [
            'mate_head' => '积分明细',
            'data'      => $records,
            'integral'  => $integral
        ]);
    }


    /**
     * 兑换积分商品页面
     * @param Request $request
     * @param MemberModel $member
     * @param IntegralGoodsModel $goodsModel
     * @param MemberAddressModel $addressModel
     * @return mixed
     */
    public function exchange(Request $request, MemberModel $member, IntegralGoodsModel $goodsModel, MemberAddressModel $addressModel)
    {
        $id = $request->get('goods_id');   //积分商品id

        //查找商品详情
        $data = $goodsModel->where('id', $id)->find();

        //用户默认收货地址
        $address = $addressModel->where(['member_id' => Session::get('member_id'), 'status' => 1])
            ->field('id,name,phone,address,area_info')->find();

        // 收获地址列表
        $addressList = $addressModel->where(['member_id' => Session::get('member_id')])->select()->toArray();

        //用户积分总额
        $total = $member->where('id', Session::get('member_id'))->value('integral');


        return $this->fetch('', [
            'mate_head'    => '积分商品订单确认',
            'data'         => $data,
            'address'      => $address,
            'total'        => $total,
            'address_list' => $addressList,
        ]);
    }


    /**
     * 兑换商品
     * @param Request $request
     * @param IntegralGoodsModel $integralGoods
     * @param MemberAddressModel $memberAddress
     * @return array
     */
    public function integral_conversion(Request $request, IntegralGoodsModel $integralGoods, MemberAddressModel $memberAddress)
    {
        if ($request->isPost()) {

            // 获取参数
            $goodId = $request->param('gid');
            $addressId = $request->param('address');

            // 获取兑换商品信息 和会员收货地址
            $data = $integralGoods->where('id', $goodId)->field('id,title,number,picUrl,price')->find();
            $address = $memberAddress->where('id', $addressId)->field('id,name,phone,area_info,address')->find();

            // 收货地址
            if (empty($address)) return ['code' => 402, 'message' => '没有收货地址！'];

            // 判断库存数量
            if ($data['number'] < 1) return ['code' => 402, 'message' => '商品数量不足！'];

            // 兑换人ID 兑换数量1
            $data['user_id'] = Session::get('member_id');
            $data['integral_number'] = 1;

            // 启动事务
            Db::startTrans();

            try {

                // 读取会员积分 和 商品需要积分
                $find = Db::name('member')->where(['id' => $data['user_id']])->value('integral');

                $integral = Db::name('integral_goods')->where(['id' => $goodId])->value('price');

                //判断积分是否充足
                $decIntegral = round($integral);
                if ($find < $decIntegral) return ['code' => 402, 'message' => '积分不足,无法兑换'];

                $information = [
                    'member_id'   => $data['user_id'],
                    'name'        => $address['name'],
                    'phone'       => $address['phone'],
                    'area_info'   => $address['area_info'],
                    'address'     => $address['address'],
                    'goods_id'    => $data['id'],
                    'title'       => $data['title'],
                    'number'      => $data['integral_number'],
                    'picUrl'      => $data['picUrl'],
                    'integral'    => $integral,
                    'status'      => '1',
                    'create_time' => time()
                ];

                // 添加
                Db::name('member_integral')->insert($information);

                // 扣除积分
                $decIntegral = round($integral);

                Db::name('member')->where(['id' => $data['user_id']])->setDec('integral', $decIntegral);

                // 扣除库存
                Db::name('integral_goods')->where(['id' => $goodId])->setDec('number', $data['integral_number']);

                // 添加记录
                Db::name('integral_record')->insert(
                    [
                        'member_id'   => $data['user_id'],
                        'type_id'     => '2',
                        'type'        => '兑换',
                        'integral'    => $decIntegral,
                        'title'       => '兑换' . $data['title'],
                        'create_time' => time()
                    ]
                );

                // 提交事务
                Db::commit();

                return ['code' => 200, 'message' => '兑换成功'];

            } catch (\Exception $e) {

                // 回滚事务
                Db::rollback();

                return ['code' => 401, 'message' => '网络繁忙'];
            }
        }
    }


    /**
     * 我的积分明细
     * @param MemberModel $member
     * @param IntegralRecordModel $integralRecord
     * @param GoodsTypeModel $goodsType
     * @return mixed
     */
    public function my_integral(MemberModel $member, IntegralRecordModel $integralRecord, GoodsTypeModel $goodsType)
    {
        // 会员ID
        $member_id = Session::get('member_id');

        // 会员信息
        $find = $member->where('id', $member_id)->field('integral,id')->find();

        // 积分收支信息
        $data = $integralRecord->where('member_id', $member_id)->order('create_time','desc')->paginate(5, false);



        return $this->fetch('', [
            'mate_head' => '我的积分',
            'find'      => $find,
            'data'      => $data
        ]);

    }

    /**
     * 改变地址
     */
    public function change_address()
    {
        // 获取地址ID
        $id = Request::instance()->param('id');

        $data = MemberAddressModel::get($id);

        if ($data) {
            return ['code'=>200,'area_info'=>$data['area_info'],'address'=>$data['address'],'name'=>$data['name'],'phone'=>$data['phone']];
        }
    }
}